package com.tadpole.music.view.activity.home;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tadpole.music.R;
import com.tadpole.music.adapter.home.DayAdapter;
import com.tadpole.music.adapter.home.RankAdapter;
import com.tadpole.music.adapter.home.WeekAdapter;
import com.tadpole.music.bean.home.ClockInBean;
import com.tadpole.music.bean.home.ClockInRankBean;
import com.tadpole.music.bean.home.ClockInRecordBean;
import com.tadpole.music.bean.home.GoClockInBean;
import com.tadpole.music.bean.home.UserInfoBean;
import com.tadpole.music.config.Constant;
import com.tadpole.music.iView.home.ClockInIView;
import com.tadpole.music.iView.home.ClockInRankIView;
import com.tadpole.music.iView.home.ClockInRecordIView;
import com.tadpole.music.iView.home.UserInfoIView;
import com.tadpole.music.presenter.home.ClockInPresenter;
import com.tadpole.music.presenter.home.ClockInRankPresenter;
import com.tadpole.music.presenter.home.ClockInRecordPresenter;
import com.tadpole.music.presenter.home.UserInfoPresenter;
import com.tadpole.music.utils.DateUtils;
import com.tadpole.music.utils.Mutils;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.ScreenshotUtil;
import com.tadpole.music.utils.StatusBarUtil;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.view.activity.base.BaseActivity;
import com.tadpole.music.view.event.JumpOneEvent;
import com.tadpole.music.view.widget.ClockInPopSuccess;
import com.tadpole.music.view.widget.NiceImageView;
import com.tadpole.music.view.widget.ShareDialog;
import com.tadpole.music.view.widget.ShareDialogUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 打卡
 * Created By 孙岩
 * on 2020/12/9
 */
public class ClockInActivity extends BaseActivity implements ClockInRecordIView, ClockInRankIView, UserInfoIView, ClockInIView {
    //回退
    private View view_back_icon;
    //立即打卡
    private TextView tvClockIn;
    //累计打卡多少天
    private TextView tvAllCount;
    //连续打卡多少天
    private TextView tvCount;
    //日期
    private TextView tvDate;
    //星期recyclerView
    private RecyclerView rvWeek;
    //星期adapter
    private WeekAdapter weekAdapter;
    //星期数据
    private List<String> weekList;
    //天recyclerView
    private RecyclerView rvDay;
    //天adapter
    private DayAdapter dayAdapter;
    //天数的数据
    private List<ClockInBean> dayList;
    //排行榜
    private RecyclerView rvRank;
    //adapter
    private RankAdapter rankAdapter;
    //我的排行
    private RelativeLayout rlMe;
    //我的名次
    private TextView tvNumber;
    //我的头像
    private NiceImageView ivImage;
    //我的昵称
    private TextView tvName;
    //我的累计打卡
    private TextView tvClockDay;
    //积分
    private TextView tvJiFen;
    //积分数量
    private TextView tvJiFenCount;
    //累计打卡
    private int clockDay;
    //获取打卡记录
    private ClockInRecordPresenter clockInRecordPresenter;
    //获取打卡排行
    private ClockInRankPresenter clockInRankPresenter;
    //获取用户信息
    private UserInfoPresenter userInfoPresenter;
    //打卡
    private ClockInPresenter clockInPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock_in);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //将头部状态栏置为透明
        StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null);
        initViews();
        initListeners();
        initData();

        //打卡记录
        clockInRecordPresenter = new ClockInRecordPresenter();
        clockInRecordPresenter.attachView(this);
        clockInRecordPresenter.getRecord();

        //打卡排行
        clockInRankPresenter = new ClockInRankPresenter();
        clockInRankPresenter.attachView(this);
        clockInRankPresenter.getClockInRank();

        //用户信息
        userInfoPresenter = new UserInfoPresenter();
        userInfoPresenter.attachView(this);

        //打卡
        clockInPresenter = new ClockInPresenter();
        clockInPresenter.attachView(this);
    }

    //初始化控件
    private void initViews() {
        view_back_icon = findViewById(R.id.view_back_icon);
        tvClockIn = findViewById(R.id.tvClockIn);
        tvAllCount = findViewById(R.id.tvAllCount);
        tvCount = findViewById(R.id.tvCount);
        tvDate = findViewById(R.id.tvDate);
        rvWeek = findViewById(R.id.rvWeek);
        rvDay = findViewById(R.id.rvDay);
        rvRank = findViewById(R.id.rvRank);
        rlMe = findViewById(R.id.rlMe);
        tvNumber = findViewById(R.id.tvNumber);
        ivImage = findViewById(R.id.ivImage);
        tvName = findViewById(R.id.tvName);
        tvClockDay = findViewById(R.id.tvClockDay);
        tvJiFen = findViewById(R.id.tvJiFen);
        tvJiFenCount = findViewById(R.id.tvJiFenCount);
    }

    //初始化监听器
    private void initListeners() {
        view_back_icon.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                ClockInActivity.this.finish();
            }
        });

        //立即打卡
        tvClockIn.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    clockInPresenter.goClockIn();
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });
    }

    //初始化数据
    private void initData() {
        tvDate.setText(DateUtils.getCurrentYearAndMonth());


        //星期数据
        weekList = new ArrayList<>();
        weekList.add("日");
        weekList.add("一");
        weekList.add("二");
        weekList.add("三");
        weekList.add("四");
        weekList.add("五");
        weekList.add("六");

        GridLayoutManager layoutManager = new GridLayoutManager(ClockInActivity.this, 7);
        rvWeek.setLayoutManager(layoutManager);
        //创建适配器
        weekAdapter = new WeekAdapter(ClockInActivity.this, weekList);
        //给RecyclerView设置适配器
        rvWeek.setAdapter(weekAdapter);

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void showRecord(ClockInRecordBean.DataBean bean) {
        //累计打卡
        clockDay = bean.getSign().getTotal_sign_days();
        //天数数据
        //获取当月天数
        dayList = new ArrayList<>();
        int maxDay = DateUtils.getCurrentMonthLastDay();
        for (int i = 0; i < DateUtils.getFirstDayOfMonth() - 1; i++) {
            //DateUtil.getFirstDayOfMonth()获取当月第一天是星期几，星期日是第一天，依次类推 0为空 false签到状态为false
            dayList.add(new ClockInBean(0, false));
        }

        for (int i = 0; i < maxDay; i++) {
            dayList.add(new ClockInBean(i + 1, false));
        }

        if (bean.getLogs().getLogs().size() == 0) {

        } else {
            for (int j = 0; j < bean.getLogs().getLogs().size(); j++) {
                for (int a = 0; a < dayList.size(); a++) {
                    if (bean.getLogs().getLogs().get(j) == dayList.get(a).getDay()) {
                        dayList.get(a).setClock(true);
                    }
                }
            }
        }

        GridLayoutManager layoutManager1 = new GridLayoutManager(ClockInActivity.this, 7);
        rvDay.setLayoutManager(layoutManager1);
        //创建适配器
        dayAdapter = new DayAdapter(ClockInActivity.this, dayList);
        //给RecyclerView设置适配器
        rvDay.setAdapter(dayAdapter);
        rvDay.setNestedScrollingEnabled(false);

        //累计打卡
        tvAllCount.setText(bean.getSign().getTotal_sign_days() + "");

        //连续打卡
        tvCount.setText(bean.getSign().getContinue_sign_days() + "");

        //积分数量
        tvJiFenCount.setText(bean.getSign_points()+"");

        //积分
        tvJiFen.setText(bean.getPoints()+"");

        if(bean.isSigned()){
            tvClockIn.setBackgroundResource(R.drawable.button_gray);
        }else{
            tvClockIn.setBackgroundResource(R.drawable.button_clock_in);
        }

    }

    @Override
    public void showClockInRank(ClockInRankBean.DataBean dataBean) {
        if (dataBean == null || dataBean.getRank() != 0) {
            rlMe.setVisibility(View.GONE);
        } else {
            rlMe.setVisibility(View.VISIBLE);
            tvNumber.setText("未上榜");
            userInfoPresenter.getUserInfo();
        }

        LinearLayoutManager layoutManager2 = new LinearLayoutManager(ClockInActivity.this, LinearLayoutManager.VERTICAL, false);
        rvRank.setLayoutManager(layoutManager2);
        //创建适配器
        rankAdapter = new RankAdapter(ClockInActivity.this, dataBean);
        //给RecyclerView设置适配器
        rvRank.setAdapter(rankAdapter);
        rvRank.setNestedScrollingEnabled(false);


    }

    @Override
    public void showUserInfo(UserInfoBean.DataBean bean) {
        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.mipmap.app_icon)
                .error(R.mipmap.app_icon)
                .priority(Priority.HIGH)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(this).load(bean.getAvatar()).apply(requestOptions).into(ivImage);

        tvName.setText(bean.getNickname());

        tvClockDay.setText(clockDay + "");

    }

    @Override
    public void noLogin() {

    }

    @Override
    public void showClockInResult(final GoClockInBean.DataBean bean) {
        clockInRecordPresenter.getRecord();
        clockInRankPresenter.getClockInRank();
        final ClockInPopSuccess popup = new ClockInPopSuccess(ClockInActivity.this, bean);
        popup.setPopupWindowFullScreen(true);
        popup.showPopupWindow();
        popup.setModeListener(new ClockInPopSuccess.IClockInMode() {
            @Override
            public void getMode(int mode, final LinearLayout llBg) {
                if (Mutils.isNetworkAvailable()) {
                    if (mode == 1) {//答题
                        EventBus.getDefault().post(new JumpOneEvent());
                        popup.dismiss();
                        ClockInActivity.this.finish();
                    } else if (mode == 2) {//分享
                        final ShareDialog dialog = new ShareDialog(ClockInActivity.this, R.style.Dialog_NoTitle);
                        dialog.show();
                        dialog.setShareListener(new ShareDialog.IShare() {
                            @Override
                            public void getShareMode(int mode) {
                                if (mode == 1) {//分享到微信
                                    shareWeChat(1, bean.getShare().getThumb(), bean.getShare().getTitle(), bean.getShare().getDesc(),bean.getShare().getUrl());

                                } else if (mode == 2) {//分享到朋友圈
                                    shareWeChat(2, bean.getShare().getThumb(), bean.getShare().getTitle(), bean.getShare().getDesc(),bean.getShare().getUrl());
                                } else if (mode == 3) {//保存到本地
                                    //截图并保存到相册     需要读写权限
                                    ScreenshotUtil.saveScreenshotFromView(llBg, ClockInActivity.this);
                                    popup.dismiss();
                                } else {
                                    dialog.dismiss();
                                }
                                dialog.dismiss();
                            }
                        });
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });
    }

    @Override
    public void show202(String str) {
        ToastUtils.show(str);
    }

    /**
     * 分享到微信好友朋友圈
     * @param mode    1好友2朋友圈
     * @param image   作品图片
     * @param title   作品标题
     * @param content 作品内容
     * @param url 跳转路径
     */
    //微信分享
    private void shareWeChat(final int mode, final String image, final String title, final String content, final String url) {
        Glide.with(this).asBitmap().load(image).into(new SimpleTarget<Bitmap>() {
            /**
             * 成功的回调
             */
            @Override
            public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
                // 下面这句代码是一个过度dialog，因为是获取网络图片，需要等待时间
                if(mode==1){
                    ShareDialogUtils.shareImage(ClockInActivity.this , url,title, content, bitmap,true);
                }else if(mode==2){
                    ShareDialogUtils.shareImage(ClockInActivity.this, url,title, content, bitmap,false);
                }
            }

            /**
             * 失败的回调
             */
            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                if(mode==1){
                    ShareDialogUtils.shareImage(ClockInActivity.this, url,title, content, null,true);
                }else if(mode==2){
                    ShareDialogUtils.shareImage(ClockInActivity.this,url,title, content, null,false);
                }
            }
        });
    }
}
